# -*- coding: utf-8 -*-

# 导入需要的包
import requests
import hashlib
import time
import smtplib
import logging
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from datetime import datetime

# 指定梦网相关信息
url = "http://61.145.229.28:7902/sms/v2/std/get_balance"
userid = [
    "JS8619",
    "JS8620",
    "JS9015",
    "JS4855",
    "JS8528",
    "JS8529",
    "JS8595",
    "JS8596",
]
pwd = ["868125", "868125", "256310", "265210", "171328", "171329", "456888", "456777"]

# 获取时间戳
timestamp = time.strftime("%m%d%H%M%S", time.localtime())

# 定义输出空列表
result_uid = []
result_json = []
blance_list = []

# 设置日志
log_file_path = "/data/python/log/monitor_sms_balance.log"  # 指定日志文件路径
logging.basicConfig(
    filename=log_file_path,
    level=logging.INFO,
    format="%(asctime)s - %(levelname)s - %(message)s",
    datefmt="%Y-%m-%d %H:%M:%S",
)


def connect_to_server():
    smtp_server = "smtp.mxhichina.com"
    port = 80
    sender_email = "noreply@pingcl.com"
    password = "p2q7hDokTA%BpmG"
    try:
        server = smtplib.SMTP(smtp_server, port)
        server.ehlo()
        server.starttls()
        server.ehlo()
        server.login(sender_email, password)
        logging.info("邮件服务器连接成功。\n")
        return server
    except Exception as e:
        logging.error("无法连接邮件服务器：" + str(e) + "\n")
        raise


def Send_Mail(msg):
    # 获取当前日期和时间
    now = datetime.now()
    server = connect_to_server()

    sender_email = "noreply@pingcl.com"
    receiver_email = [
        "runfa.li@pingcl.com",  # "taoming.zhou@pingcl.com"
    ]

    subject = f"告警-梦网短信发送量({now})"
    # 将messages中的文本加粗，整个消息使用HTML格式
    message = (
        f"您好！<br>梦网短信发送量疑似异常：<br><strong>{msg}</strong><br>请关注！"
    )

    email = MIMEMultipart()
    email["From"] = sender_email
    email["To"] = ", ".join(receiver_email)
    email["Subject"] = subject
    # 将邮件正文格式设置为HTML
    email.attach(MIMEText(message, "html"))

    try:
        server.send_message(email)
        server.quit()
        logging.info("邮件发送成功！\n")
    except Exception as e:
        logging.error("邮件发送失败：\n" + str(e))
        raise


# 获取uid和对应的json信息
def getBlance():
    logging.info("开始获取余量信息")
    for uid, upwd in zip(userid, pwd):
        logging.info(f"正在处理用户 {uid}")
        # 明文密码 MD5 加密
        tempPwd = uid.upper() + "00000000" + upwd + timestamp
        md5 = hashlib.md5()
        md5.update(tempPwd.encode("utf-8"))
        md5Pwd = md5.hexdigest()

        # 定义字典
        data = {
            "userid": uid,
            "pwd": md5Pwd,
            "timestamp": timestamp,
        }

        try:
            # 获取 json
            response = requests.post(url, data=data)
            result = response.json()
            result_uid.append(uid)
            result_json.append(result)
            logging.info(f"用户 {uid} 获取余量信息成功")
        except Exception as e:
            logging.error(f"用户 {uid} 获取余量信息失败：{e}")
    return result_uid, result_json


# 获取各个账号余量
def Blance():
    logging.info("开始解析各个账号余量")
    for uid, result in zip(result_uid, result_json):
        if result["result"] == 0:
            balance = int(result["balance"])
            blance_list.append(balance)
            logging.info(f"用户 {uid} 余量为 {balance}")
        else:
            msg = f"* {uid} 查询失败，错误码为：{result['result']}*"
            Send_Mail(msg)
            logging.warning(msg)
    return blance_list


"""
# 获取各个账号余量
def Blance():
    for uid, result in zip(result_uid, result_json):
        if result["result"] == 0:
            if uid == "JS8619":
                sms_balance_8619 = int(result["balance"])
                blance_list.append(sms_balance_8619)
            if uid == "JS8620":
                sms_balance_8620 = int(result["balance"])
                blance_list.append(sms_balance_8620)
            if uid == "JS9015":
                sms_balance_9015 = int(result["balance"])
                blance_list.append(sms_balance_9015)
            if uid == "JS4855":
                sms_balance_4855 = int(result["balance"])
                blance_list.append(sms_balance_4855)
            if uid == "JS8528":
                sms_balance_8528 = int(result["balance"])
                blance_list.append(sms_balance_8528)
            if uid == "JS8529":
                sms_balance_8529 = int(result["balance"])
                blance_list.append(sms_balance_8529)
            if uid == "JS8595":
                sms_balance_8595 = int(result["balance"])
                blance_list.append(sms_balance_8595)
            if uid == "JS8596":
                sms_balance_8596 = int(result["balance"])
                blance_list.append(sms_balance_8596)
        else:
            msg = "* " + uid + " 查询失败，错误码为：{}*".format(result["result"])
            Send_Mail(msg)
    return blance_list
"""


# 获取当前时间
def nowTime():
    now = datetime.now()
    # 将时间格式化为字符串
    formatted_time = now.strftime("%Y-%m-%d %H:%M:%S")
    return formatted_time


# 获取当前余量
old_time = nowTime()
old_result_uid, old_result_json = getBlance()
old = Blance()
result_uid = []
result_json = []
blance_list = []

print("{} old 值 {}".format(old_time, old))
logging.info(f"{old_time} old 值 {old}")

# 暂停10分钟
logging.info("开始10分钟等待")
time.sleep(600)
logging.info("10分钟等待结束")

# 获取当前余量
new_time = nowTime()
new_result_uid, new_result_json = getBlance()
new = Blance()
result_uid = []
result_json = []
blance_list = []

print("{} new 值 {}".format(new_time, new))
logging.info(f"{new_time} new 值 {new}")

# 开始做判断
if old[0] - new[0] < 200:
    nowtime = nowTime()
    print("{} JS8619 无异常。".format(nowtime))
    logging.info(f"{nowtime} JS8619 无异常。")
    if new[0] < 30000:
        nowtime = nowTime()
        now_blance = new[0]
        msg = (
            "*温馨提示：{} 新浪健康(生产账号) JS8619 ".format(nowtime)
            + "当前余量为 {}, ".format(now_blance)
            + "少于 30000 条, 请关注! *"
        )
        print(msg)
        Send_Mail(msg)
else:
    nowtime = nowTime()
    now_blance = new[0]
    send_sum_msg = old[0] - new[0]
    msg = (
        "*温馨提示：{} 新浪健康(生产账号) JS8619 ".format(nowtime)
        + "当前余量为 {}, ".format(now_blance)
        + "最近十分钟发送量为 {}, 超 200 条, 请关注! *".format(send_sum_msg)
    )
    print(msg)
    Send_Mail(msg)

if old[1] - new[1] < 200:
    nowtime = nowTime()
    print("{} JS8620 无异常。".format(nowtime))
    logging.info(f"{nowtime} JS8620 无异常。")
    if new[1] < 30000:
        nowtime = nowTime()
        now_blance = new[1]
        msg = (
            "*温馨提示：{} 新浪健康(服务账号) JS8620 ".format(nowtime)
            + "当前余量为 {}, ".format(now_blance)
            + "少于 30000 条, 请关注! *"
        )
        print(msg)
        Send_Mail(msg)
else:
    nowtime = nowTime()
    now_blance = new[1]
    send_sum_msg = old[1] - new[1]
    msg = (
        "*温馨提示：{} 新浪健康(服务账号) JS8620 ".format(nowtime)
        + "当前余量为 {}, ".format(now_blance)
        + "最近十分钟发送量为 {}, 超 200 条, 请关注! *".format(send_sum_msg)
    )
    print(msg)
    Send_Mail(msg)

if old[2] - new[2] < 200:
    nowtime = nowTime()
    print("{} JS9015 无异常。".format(nowtime))
    logging.info(f"{nowtime} JS9015 无异常。")
    if new[2] < 10000:
        nowtime = nowTime()
        now_blance = new[2]
        msg = (
            "*温馨提示：{} 爱问医生 JS9015 ".format(nowtime)
            + "当前余量为 {}, ".format(now_blance)
            + "少于 10000 条, 请关注! *"
        )
        print(msg)
        Send_Mail(msg)
else:
    nowtime = nowTime()
    now_blance = new[2]
    send_sum_msg = old[2] - new[2]
    msg = (
        "*温馨提示：{} 爱问医生 JS9015 ".format(nowtime)
        + "当前余量为 {}, ".format(now_blance)
        + "最近十分钟发送量为 {}, 超 200 条, 请关注! *".format(send_sum_msg)
    )
    print(msg)
    Send_Mail(msg)

if old[3] - new[3] < 200:
    nowtime = nowTime()
    print("{} JS4855 无异常。".format(nowtime))
    logging.info(f"{nowtime} JS4855 无异常。")
    if new[3] < 10000:
        nowtime = nowTime()
        now_blance = new[3]
        msg = (
            "*温馨提示：{} 营销类爱问医生 JS4855 ".format(nowtime)
            + "当前余量为 {}, ".format(now_blance)
            + "少于 10000 条, 请关注! *"
        )
        print(msg)
        Send_Mail(msg)
else:
    nowtime = nowTime()
    now_blance = new[3]
    send_sum_msg = old[3] - new[3]
    msg = (
        "*温馨提示：{} 营销类爱问医生 JS4855 ".format(nowtime)
        + "当前余量为 {}, ".format(now_blance)
        + "最近十分钟发送量为 {}, 超 200 条, 请关注! *".format(send_sum_msg)
    )
    print(msg)
    Send_Mail(msg)

if old[4] - new[4] < 200:
    nowtime = nowTime()
    print("{} JS8528 无异常。".format(nowtime))
    logging.info(f"{nowtime} JS8528 无异常。")
    if new[4] < 10000:
        nowtime = nowTime()
        now_blance = new[4]
        msg = (
            "*温馨提示：{} 爱问健康 JS8528 ".format(nowtime)
            + "当前余量为 {}, ".format(now_blance)
            + "少于 10000 条, 请关注! *"
        )
        print(msg)
        Send_Mail(msg)
else:
    nowtime = nowTime()
    now_blance = new[4]
    send_sum_msg = old[4] - new[4]
    msg = (
        "*温馨提示：{} 爱问健康 JS8528 ".format(nowtime)
        + "当前余量为 {}, ".format(now_blance)
        + "最近十分钟发送量为 {}, 超 200 条, 请关注! *".format(send_sum_msg)
    )
    print(msg)
    Send_Mail(msg)

if old[5] - new[5] < 200:
    nowtime = nowTime()
    print("{} JS8529 无异常。".format(nowtime))
    logging.info(f"{nowtime} JS8529 无异常。")
    if new[5] < 10000:
        nowtime = nowTime()
        now_blance = new[5]
        msg = (
            "*温馨提示：{} 营销类爱问健康 JS8529 ".format(nowtime)
            + "当前余量为 {}, ".format(now_blance)
            + "少于 10000 条, 请关注! *"
        )
        print(msg)
        Send_Mail(msg)
else:
    nowtime = nowTime()
    now_blance = new[5]
    send_sum_msg = old[5] - new[5]
    msg = (
        "*温馨提示：{} 营销类爱问健康 JS8529 ".format(nowtime)
        + "当前余量为 {}, ".format(now_blance)
        + "最近十分钟发送量为 {}, 超 200 条, 请关注! *".format(send_sum_msg)
    )
    print(msg)
    Send_Mail(msg)

if old[6] - new[6] < 200:
    nowtime = nowTime()
    print("{} JS8595 无异常。".format(nowtime))
    logging.info(f"{nowtime} JS8595 无异常。")
    if new[6] < 10000:
        nowtime = nowTime()
        now_blance = new[6]
        msg = (
            "*温馨提示：{} 爱问社区 JS8595 ".format(nowtime)
            + "当前余量为 {}, ".format(now_blance)
            + "少于 10000 条, 请关注! *"
        )
        print(msg)
        Send_Mail(msg)
else:
    nowtime = nowTime()
    now_blance = new[6]
    send_sum_msg = old[6] - new[6]
    msg = (
        "*温馨提示：{} 爱问社区 JS8595 ".format(nowtime)
        + "当前余量为 {}, ".format(now_blance)
        + "最近十分钟发送量为 {}, 超 200 条, 请关注! *".format(send_sum_msg)
    )
    print(msg)
    Send_Mail(msg)

if old[7] - new[7] < 200:
    nowtime = nowTime()
    print("{} JS8596 无异常。".format(nowtime))
    logging.info(f"{nowtime} JS8596 无异常。")
    if new[7] < 10000:
        nowtime = nowTime()
        now_blance = new[7]
        msg = (
            "*温馨提示：{} 营销类爱问社区 JS8596 ".format(nowtime)
            + "当前余量为 {}, ".format(now_blance)
            + "少于 10000 条, 请关注! *"
        )
        print(msg)
        Send_Mail(msg)
else:
    nowtime = nowTime()
    now_blance = new[7]
    send_sum_msg = old[7] - new[7]
    msg = (
        "*温馨提示：{} 营销类爱问社区 JS8596 ".format(nowtime)
        + "当前余量为 {}, ".format(now_blance)
        + "最近十分钟发送量为 {}, 超 200 条, 请关注! *".format(send_sum_msg)
    )
    print(msg)
    Send_Mail(msg)
